from copy import deepcopy
import shelve
from config import database_path


class split_table:
    def __init__(self, config: dict, ) -> None:
        self.input_table_name = config["input_table"]
        self.output_table_name = config.get("output_table", self.input_table_name)
        self.args: dict = config["args"]
        type = config["type"]
        self.output_table = []
        
        with shelve.open(database_path,writeback=True) as db:
            self.input_table =deepcopy(db['tables_dict'][self.input_table_name])
            if type == "row":
                self.__row()
            elif type == "column":
                self.__column()
            db['tables_dict'][self.output_table_name]=self.output_table
            


    def __row(self):
        {
            "action": "split",
            "type": "row",
            "input_table": "input_table",
            "output_table": "output_table",
            "args": {
                "column": "列1",
                "split": "_"
            }
        }
        column = self.args['column']
        split = self.args['split']
        for rowdict in self.input_table:
            # row = deepcopy(rowdict)
            column_value = str(rowdict.get(column, ''))
            for onecolumn in column_value.split(split):
                rowdict[column] = onecolumn
                c = deepcopy(rowdict)
                self.output_table.append(c)

    def __column(self):
        {
            "action": "split",
            "type": "column",
            "input_table": "in_table",
            "output_table": "out_table",
            "args": {
                "split": "_",
                "column": "列1",
                "newcolumns": [
                    {"columname": "列1", "num": 0},
                    {"columname": "列2", "num": 2}
                ]
            }
        }
        column = self.args['column']
        split = self.args['split']
        newcolumns = self.args['newcolumns']
        for rowdict in self.input_table:
            # row = deepcopy(rowdict)
            column_value = str(rowdict.get(column, ''))
            column_value_list = column_value.split(split)
            for columninfo in newcolumns:
                columname = columninfo['columname']
                num = columninfo['num']
                try:
                    value = column_value_list[num]
                except IndexError:
                    value = ''
                rowdict.update({columname: value})
            c = deepcopy(rowdict)
            self.output_table.append(c)
